package com.origin.hook

import org.junit.Test

import org.junit.Assert.*
import com.origin.hook.test.Child

import com.origin.hook.test.MyClassLoader

import org.objectweb.asm.Opcodes.ASM9

import com.origin.hook.test.ChildClassVisitor
import org.objectweb.asm.ClassReader
import org.objectweb.asm.ClassVisitor
import org.objectweb.asm.ClassWriter
import java.io.FileOutputStream
import java.lang.Exception


/**
 * Example local unit test, which will execute on the development machine (host).
 *
 * See [testing documentation](http://d.android.com/tools/testing).
 */
class ExampleUnitTest {
    @Test
    fun addition_isCorrect() {
        assertEquals(4, 2 + 2)
        startHook()
    }
    val LOCAL_PATH =
        "E:\\project\\Android\\android-origin\\hook\\build\\intermediates\\javac\\debug\\classes\\com\\origin\\hook\\test\\Child.class"
    private fun startHook() {
        try {
            //1.首先创建ClassReader,读取目标类Child的内容
            val cr = ClassReader(Child::class.java.name)
            //2.然后创建ClassWriter对象，
            val cw = ClassWriter(cr, ClassWriter.COMPUTE_MAXS)
            val cv: ClassVisitor = ChildClassVisitor(ASM9, cw)
            cr.accept(cv, ASM9)
            // 获取生成的class文件对应的二进制流
            val code: ByteArray = cw.toByteArray()
            val myClassLoader = MyClassLoader()
            myClassLoader.getClassByBytes(code)
            //            //将二进制流写到out/下
            val fos =  FileOutputStream(LOCAL_PATH);
            fos.write(code);
            fos.close();
            val child = Child()
            child.call()
        } catch (e: Exception) {
            println("xxx===>$e")
            e.printStackTrace()
        }
    }
}